package tool

import java.io.File
import java.net.URLEncoder
import scala.annotation.tailrec

/** Created by yz on 6/4/2021
  */
object Tool {

  val filePathSeparators = Array('/', '\\', File.separatorChar).distinct

  def fileLikeCanonicalPath(path: String): String = {
    @tailrec
    def normalizePathSegments(accumulated: Seq[String], remaining: List[String]): Seq[String] = {
      remaining match {
        case Nil =>
          accumulated
        case "." :: rest =>
          normalizePathSegments(accumulated, rest)
        case ".." :: rest =>
          val newAccumulated = if (accumulated.isEmpty) Seq("..") else accumulated.dropRight(1)
          normalizePathSegments(newAccumulated, rest)
        case segment :: rest =>
          normalizePathSegments(accumulated :+ segment, rest)
      }
    }
    val splitPath: List[String] = path.split(filePathSeparators).toList
    val splitNormalized: Seq[String] = normalizePathSegments(Vector.empty, splitPath)
    splitNormalized.mkString("/")
  }

  def underFileOp(path: String, fileName: String) = {
    val resourceName = s"${path}/${fileName}"
    if (fileLikeCanonicalPath(resourceName).startsWith(fileLikeCanonicalPath(path))) {
      Some(new File(path, fileName))
    } else None
  }

  def urlEncode(url: String) = {
    URLEncoder.encode(url, "UTF-8")
  }

  def getContentDisposition(url: String) = {
    val encodeUrl = Tool.urlEncode(url)
    s"attachment; filename*=utf-8''${encodeUrl}"
  }

}
